package org.lagou.edu.mvcframework.servlet;

import org.apache.commons.lang3.StringUtils;
import org.lagou.edu.mvcframework.annotations.JyAutowired;
import org.lagou.edu.mvcframework.annotations.JyController;
import org.lagou.edu.mvcframework.annotations.JyRequestMapping;
import org.lagou.edu.mvcframework.annotations.JyService;
import org.lagou.edu.mvcframework.pojo.Handler;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author junbao
 */
public class JyDispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<>();

    private Map<String, Object> iocMap = new HashMap<>();

    //private Map<String, Method> handlerMapping = new HashMap<>();
    private List<Handler> handlerList = new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1. 加载配置文件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        // 2. 扫描相关的类， 扫描注解
        doScan(properties.getProperty("scanPackage"));

        // 3. 初始化bean对象(实现IOC容器，基于注解)
        doInstance();

        // 4. 实现依赖注入
        doAutoWird();

        // 5. 构造一个HandlerMapping处理器映射器，将配置好的url和Method建立映射关系
        initHandlerMapping();

        System.out.println("lagou mvc 初始化完成...");

        // 6. 等待请求进入，处理请求
    }

    // 构造一个HandlerMapper处理器映射器
    // 最关键的环节：将url与method关联
    private void initHandlerMapping() {

        if(iocMap.size() == 0) {
            return;
        }

        for(Map.Entry<String, Object> entry : iocMap.entrySet()) {
            // 获取容器中当前遍历的class类型
            Class<?> aClass = entry.getValue().getClass();

            if(aClass.isAnnotationPresent(JyController.class)) {
                String baseUrl = "";
                if(aClass.isAnnotationPresent(JyRequestMapping.class)) {
                    JyRequestMapping annotation = aClass.getAnnotation(JyRequestMapping.class);
                    baseUrl = annotation.value();
                }
                // 获取方法
                Method[] methods = aClass.getMethods();
                for (int i = 0; i < methods.length; i++) {
                    Method method = methods[i];
                    if(method.isAnnotationPresent(JyRequestMapping.class)) {
                        //方法也有@JyRequestMapping注解
                        JyRequestMapping annotation = method.getAnnotation(JyRequestMapping.class);
                        String methodUrl = annotation.value();
                        String url = baseUrl + methodUrl;

                        // 建立联系
                        // handlerMapping.put(url, method);

                        // 封装Handler
                        Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));
                        Parameter[] parameters = method.getParameters();
                        for (int j = 0; j < parameters.length; j++) {
                            Parameter parameter = parameters[j];
                            if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                                handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), j);
                            }else {
                                handler.getParamIndexMapping().put(parameter.getName(), j);
                            }
                        }
                        handlerList.add(handler);

                    }else {
                        continue;
                    }
                }
            }else{
                continue;
            }
        }


    }

    // 依赖注入
    private void doAutoWird() {

        if(iocMap.size() == 0) {return;}

        // 有对象，进行依赖注入

        // 遍历ioc容器中的所有对象，判断是否有@JyAutowired注解
        for(Map.Entry<String, Object> entry : iocMap.entrySet()) {
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            for (int i = 0; i < declaredFields.length; i++) {
                Field declaredField = declaredFields[i];
                if(declaredField.isAnnotationPresent(JyAutowired.class)) {
                    //有注解
                    JyAutowired annotation = declaredField.getAnnotation(JyAutowired.class);
                    String beanName = annotation.value();
                    if("".equals(beanName)) {
                        //没有配置具体的bean id，需要根据接口注入
                        beanName = declaredField.getType().getName();
                    }
                    declaredField.setAccessible(true);
                    try {
                        declaredField.set(entry.getValue(), iocMap.get(beanName));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }else {
                    continue;
                }

            }
        }
    }

    // ioc容器
    
    // 基于classNames缓存的类的全限定类名，以及反射技术，完成对象创建和管理
    private void doInstance(){
        
        if(classNames.size() == 0) {
            return;
        }

        for (int i = 0; i < classNames.size(); i++) {
            String className =  classNames.get(i);

            // 反射
            try {
                Class<?> aClass = Class.forName(className);
                // 区分controller service
                if(aClass.isAnnotationPresent(JyController.class)) {
                    String simpleName = aClass.getSimpleName();
                    String lowFirstSimpleName = lowerFirst(simpleName);
                    Object o = aClass.newInstance();
                    iocMap.put(lowFirstSimpleName, o);
                }else if(aClass.isAnnotationPresent(JyService.class)) {
                    JyService annotation = aClass.getAnnotation(JyService.class);
                    // 获取注解的value值
                    String beanName = annotation.value();
                    if(!"".equals(beanName.trim())) {
                        iocMap.put(beanName,aClass.newInstance());
                    }else{
                        beanName = lowerFirst(aClass.getSimpleName());
                        iocMap.put(beanName,aClass.newInstance());
                    }

                    // Service继承接口，以接口名作为key放入一份到容器中，便于后期根据接口注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (int j = 0; j < interfaces.length; j++) {
                        Class<?> anInterface = interfaces[j];
                        // 以接口的全限定类名作为id放入
                        iocMap.put(anInterface.getName(),aClass.newInstance());
                    }
                }else {
                    continue;
                }

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
        
        
        
    }

    // 首字母小写方法
    public String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        if('A' <= chars[0] && chars[0] < 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    // 扫描类
    private void doScan(String scanPackage) {
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);
        File[] files = pack.listFiles();
        for(File file : files) {
            if(file.isDirectory()) {
                doScan(scanPackage + "." + file.getName());
            }else if(file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }else {
                continue;
            }
        }
    }

    // 加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理请求

        // 根据uri获取到能够处理当前请求的Handler(从handlermapping中(list))
        Handler handler = getHandler(req);
        if(handler == null) {
            resp.getWriter().write("404 not found");
            return;
        }

        // 绑定参数
        // 获取所有参数类型数据，这个数据的长度就是args数组的长度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();

        // 向参数数组中set值，且保证参数的顺序和方法中的形参顺序一致
        Object[] paraValues = new Object[parameterTypes.length];

        Map<String, String[]> parameterMap = req.getParameterMap();

        // 遍历request中所有参数
        for(Map.Entry<String, String[]> param: parameterMap.entrySet()) {
            String value = StringUtils.join(param.getValue(), ",");
            // 填充参数
            if(handler.getParamIndexMapping().containsKey(param.getKey())) {
                // 方法形参中确实有该参数，找到它的索引位置，对应的把参数值放入paraValues
                Integer index = handler.getParamIndexMapping().get(param.getKey());
                paraValues[index] = value;
            }else {
                continue;
            }
        }

        Integer reqIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        Integer respIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paraValues[reqIndex] = req;
        paraValues[respIndex] = resp;

        // 最终调用handler的method属性
        try {
            handler.getMethod().invoke(handler.getController(), paraValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private Handler getHandler(HttpServletRequest req) {

        if(handlerList.size() == 0) {return null;}

        String url = req.getRequestURI();

        for(Handler handler: handlerList) {
            Matcher matcher = handler.getPattern().matcher(url);
            if(matcher.matches()) {
                return handler;
            }else {
                continue;
            }
        }

        return null;
    }


}
